//
//  PVDDetailModel.swift
//  ezyform
//
//  Created by MoennigQ on 16/5/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
class PVDDetailModel: HandyJSON {
    var pvd_id : Int64 = 0
    var id: String {
        return String(pvd_id)
    }
    //给installer的说明
    var installer_job_site_instruction: String = ""{
        didSet{
            JobDetailModelHelper.shared.installer_job_site_instruction.onNext(installer_job_site_instruction)
        }
    }
    var solar_water_heater: Bool = false//为 true 时是 swh , 为 false 时是  solar
    var gst: Bool = false
    var gwt_id: String = ""{//当前Job是否开启SPV
        didSet{
            JobDetailModelHelper.shared.gwt_id.onNext(gwt_id)
        }
    }
    //job status: 0 is scheduled; 1: installing; 2 installed; 3 unqulified
    var job_status: String = "" {
        didSet{
            JobDetailModelHelper.shared.job_status.onNext(job_status)
        }
    }
    //retailer company name
    var company: String = ""
    var company_id: Int = 0
    var company_electrical_contractor_license_number: String  = ""
    var company_electrical_contractor_Name: String  = ""
    var company_electrical_contractor_phone_number: String  = ""
    //SPV
    var company_spv_check: Bool = false //retailer设置的是否开启SPV的值
    var installation_position_deviation: Double  = 0 //系统设置的panel number的安装位置和最初位置偏移的最大距离，单位是米
    var spv_check: Bool = false  {//当前Job是否开启SPV
        didSet{
            JobDetailModelHelper.shared.spv_check.onNext(spv_check)
        }
    }
    var spv_installed: Bool = false//当前Job 的Panel Number是否安装完成，验证通过
    var der_register: Bool = false//true: checklist中最后一条或finish job成功后的弹出框显示der register；false表示不显示
    //
    var arrived_at: String  = ""
    var arrived_location: String  = ""
    var finished_at: String  = ""
    var finished_location: String  = ""
    //owner address
    var owner_address = InstallationDetailOwnerAddress(){
        didSet{
            JobDetailModelHelper.shared.owner_address.onNext(owner_address)
        }
    }
    
    //real install address
    var install_address = InstallationDetailInstallAddress(){
        didSet{
            JobDetailModelHelper.shared.install_address.onNext(install_address)
        }
    }
    
    //solar system detail
    var system_detail = InstallationDetailSystemDetail() {
        didSet{
            //处理热水器的两个标志，从里边复制到外边
            if self.solar_water_heater, self.system_detail.heaters.count > 0 {
                self.system_detail.heaters[0].second_hand_flg = self.system_detail.second_hand_flg
                self.system_detail.heaters[0].multi_heater_flg = self.system_detail.multi_heater_flg
            }
            JobDetailModelHelper.shared.system_detail.onNext(system_detail)
        }
    }
    
    //checklist,备注：因为pvd_checklists数据要重组，里边的remove，append会触发didset，所以不能再didset中做数据通知；只能在用的地方直接通知即可
    var pvd_checklists: [PVDChecklistModel] = [PVDChecklistModel]() 
    //local checklist data
    var localChecklists: [PVDChecklistModel] = [PVDChecklistModel]()
    
    //***********New serial numbers in child table,备注：因为pvd_serial_numbers数据要重组，里边的remove，append会触发didset，所以不能再didset中做数据通知；只能在用的地方直接通知即可
    var pvd_serial_numbers: [PanelNumberImageDBModel] = [PanelNumberImageDBModel]()
    //*****deleted panelnumbers from server
    var localDeletedSerialNumbers = [PanelNumberImageDBModel]()
    
    //***********New serial numbers in child table,备注：因为pvd_inverter_serial_numbers数据要重组，里边的remove，append会触发didset，所以不能再didset中做数据通知；只能在用的地方直接通知即可
    var pvd_inverter_serial_numbers: [PanelNumberImageDBModel] = [PanelNumberImageDBModel]()
    //****deleted panelnumbers from server
    var localDeletedInverterNumbers = [PanelNumberImageDBModel]()
    //************
    var tank_serial_numbers: [PanelNumberImageDBModel] = [PanelNumberImageDBModel]()//id,code,image
    
    //owner,designer,installer signature
    var signatures: InstallationDetailSignatures  = InstallationDetailSignatures(){
        didSet{
            JobDetailModelHelper.shared.signatures.onNext(signatures)
            
            JobDetailModelHelper.shared.pvd_checklists.onNext(pvd_checklists)
        }
    }
    
    //local siginatures
    var localSignatures: PVDSignaturesLocalModel = PVDSignaturesLocalModel()
    
    //local signatures info (signed time, witness's print name)
    var localSignaturesInfo = NSMutableDictionary()
    
    //check if signatures is modified
    var signaturesModifyFlag: Bool {
        if localSignatures.installer != nil || localSignatures.designer != nil || localSignatures.owner != nil || localSignatures.witness != nil{
            return true
        }
        return false
    }
    
    //check if panel numbers is modified
    var panelNumbersModifyFlag: Bool {
        if self.localDeletedSerialNumbers.count > 0 {
            return true
        }else if let  _  = self.pvd_serial_numbers.firstIndex(where: {$0.operType == DataOperType.Add.rawValue || $0.operType == DataOperType.Modify.rawValue}){
            return true
        }
        return false
    }
    //check if inverter numbers is modified
    var inverterNumbersModifyFlag: Bool {
        if self.localDeletedInverterNumbers.count > 0 {
            return true
        }else if let  _  = self.pvd_inverter_serial_numbers.firstIndex(where: {$0.operType == DataOperType.Add.rawValue || $0.operType == DataOperType.Modify.rawValue}){
            return true
        }
        return false
    }
    //only check if checklist is modidfied
    var checkListModifyFlag: Bool {
        let localChecklist = DBManager.shared.loadAllChecklistData(pvdId: self.id)
        if localChecklist.count > 0 {
            return true
        }
        return false
    }
    //only check if installation address and date of completion
    var detailModifyFlag: Bool {
        if self.panelNumbersModifyFlag || self.inverterNumbersModifyFlag || self.checkListModifyFlag || self.signaturesModifyFlag{
            return true
        }
        return false
    }
    
    var stc_document = InstallationAttachmentModel()
    var coc_document = InstallationAttachmentModel()
    var invoice_document =  InstallationAttachmentModel()
    var other_document = [InstallationAttachmentModel]()
    //have multiple attachments,use new parameter
    var stc_documents = [InstallationAttachmentModel]()
    var coc_documents = [InstallationAttachmentModel]()
//    var invoice_documents : [InstallationAttachmentModel]?//不让installer看到这些敏感信息，3.6.0版本去掉
    var notice_of_completion_documents = [InstallationAttachmentModel]()
    //当前用户是否是Installer，true表示是可以有所有操作权限，false表示否，即当前用户是designer只能前自己的签名
    var isInstallerFlag: Bool {
        let installerAccreditation = signatures.installer_accredited_number
        let currentSaaNumber = APPConfig.loginInfo.saaNumber
        if installerAccreditation != "" &&  currentSaaNumber != "" {//installer,designer和当前登录用户的accreditation number都不会null且都不会空字符串
            //如果当前登录用户的accreditation和installer的是一致的就是installer
            if currentSaaNumber == installerAccreditation {
                return true
            }
        }
        
        
        
        let currentAccreditation = APPConfig.loginInfo.accreditedNumber
        if installerAccreditation != "" &&  currentAccreditation != "" {//installer,designer和当前登录用户的accreditation number都不会null且都不会空字符串
            //如果当前登录用户的accreditation和installer的是一致的就是installer
            if currentAccreditation == installerAccreditation{
                return true
            }
        }
        return false
    }
    //当前用户是否是designer，true表示是
    var isDesignerFlag: Bool {
        let designerAccreditation = signatures.designer_accredited_number
        
        let currentSaaNumber = APPConfig.loginInfo.saaNumber
        if designerAccreditation != "" &&  currentSaaNumber != "" {//installer,designer和当前登录用户的accreditation number都不会null且都不会空字符串
            //如果当前登录用户的accreditation和installer的是一致的就是installer
            if currentSaaNumber == designerAccreditation {
                return true
            }
        }
                
        let currentAccreditation = APPConfig.loginInfo.accreditedNumber
        if designerAccreditation != "" && currentAccreditation != "" {//installer,designer和当前登录用户的accreditation number都不会null且都不会空字符串
            //如果当前登录用户的accreditation和installer，designer的都不一致，就表示当前用户没有任何操作权限
            if currentAccreditation == designerAccreditation{
                return true
            }
        }
        return false
    }
    
    //电工表的链接路径，为null 或 '' 就不显示checklist中的，有路径的时候就显示
    var electrical_template: String = ""
    //true表示当前company是Aus Solar Co，在Owner签名时需要多前连个满意度form
    var is_aus_solar_co: Bool = false
    //Owner签字时选择的
    var physicallyAttended: String = ""
    //finish Job成功后是否弹出APP评分的标识,不为空就弹出App comment，空值不弹出
    var installer_rating_id: Int? //这里需要空值
    //true表示使用老的owner协议，否则使用新的owner协议
    var is_aho: Bool = false
    // is_new_stc_form 为 true ,表示使用新的协议，aho的协议版本传3，其他协议版本传4
    var is_new_stc_form: Bool = false
    var agent_id: Int = 0
    // is_osw_agent 为 true ,表示agent是OSW，false表示agent是非OSW，用于区分owner的mandatory_declaration
    var is_osw_agent: Bool {
        if agent_id == 1 || agent_id == 2 {
            return true
        }
        return false
    }
    var agent_name: String = ""
    var re_sign_statement_message: String = ""//如果不为空就是需要重新签名，需要提示
    //Installer,Designer是否同一个人且可以合并签名
    var isInstallerAndDesigner: Bool {
        if self.is_new_stc_form {//首先必须是新协议
            let installerAccNumber = signatures.installer_accredited_number
            let designerAccNumber = signatures.designer_accredited_number
            let designerAccType = signatures.designer_accreditation_type
            if  installerAccNumber == designerAccNumber && designerAccType.lowercased().contains("design"){//accredited_number相同，且designer有design资质
                return true
            }
        }
        return false
    }
    //当前登录角色是Designer，是否能签名
    var canDesignerSignFlag: Bool {
        let jobStatus = self.job_status
        if jobStatus != "0" &&  jobStatus != "2" && self.isDesignerFlag{//jobstatus不是scheduled,不是installed，而且当前用户是installater才能编辑pvd detail 信息
            return true
        }
        return false
    }
    //用于判断是否可以编辑Owner info, inverter ,battery,  installation type, grid connected
    var canEditJobDetailFlag: Bool {
        if self.job_status != PVDJobStatusValue.installed.rawValue && self.isInstallerFlag{
            return true
        }
        return false
    }
    //用于判断是否可以编辑panel info
    var canEditPanelInfoFlag: Bool {
        let jobStatus = self.job_status
        let spvCheckFlag = self.spv_check
        let spvInstalled = self.spv_installed
        if spvCheckFlag && spvInstalled {//panel installed之后不能编辑panel info
            return false
        }else if jobStatus != PVDJobStatusValue.installed.rawValue && self.isInstallerFlag{//jobstatus不是installed，而且当前用户是installater才能编辑panel info信
            return true
        }
        return false
    }
    var agreenments =  PVDDetailAgreenmentsModel()
    var pick_up_required: Bool = false {
        didSet{
            JobDetailModelHelper.shared.pick_up_required.onNext(pick_up_required)
        }
    }
    var pick_up_reference: String = "" {
        didSet{
            JobDetailModelHelper.shared.pick_up_reference.onNext(pick_up_reference)
        }
    }
    var delivery_address: DeliveryWarehouseModel = DeliveryWarehouseModel()
    //checklsit: Check-In Selfie是否已经完成
    var checkInSelfieDoneFlag: Bool {
        if let checklist = self.pvd_checklists.filter({$0.id == ChecklistFixedId.preInstall.rawValue}).first{
            if checklist.images.count > 0{
                return true
            }
        }
        return false
    }
    var checkInSelfieTitle: String {
        if let checklist = self.pvd_checklists.filter({$0.id == ChecklistFixedId.preInstall.rawValue}).first{
            return checklist.title
        }
        return ""
    }
    //checklsit: Mid-Installation Selfie是否已经完成
    var midInstallationSelfieDoneFlag: Bool {
        if let checklist = self.pvd_checklists.filter({$0.id == ChecklistFixedId.midInstall.rawValue}).first{
            if checklist.images.count > 0{
                return true
            }
        }
        return false
    }
    var midInstallationSelfieTitle: String {
        if let checklist = self.pvd_checklists.filter({$0.id == ChecklistFixedId.midInstall.rawValue}).first{
            return checklist.title
        }
        return ""
    }
    required init(){}
    
    func copyAllValuesOfModel(_ newModel: PVDDetailModel){
        self.pvd_id = newModel.pvd_id
        self.gwt_id = newModel.gwt_id
        self.solar_water_heater = newModel.solar_water_heater
        self.job_status = newModel.job_status
        self.company = newModel.company
        self.company_id = newModel.company_id
        self.agent_name = newModel.agent_name
        self.company_electrical_contractor_license_number = newModel.company_electrical_contractor_license_number
        self.company_electrical_contractor_Name = newModel.company_electrical_contractor_Name
        self.company_electrical_contractor_phone_number = newModel.company_electrical_contractor_phone_number
        self.company_spv_check = newModel.company_spv_check
        self.installation_position_deviation = newModel.installation_position_deviation
        self.spv_check = newModel.spv_check
        self.spv_installed = newModel.spv_installed
        self.der_register = newModel.der_register
        self.arrived_at = newModel.arrived_at
        self.arrived_location = newModel.arrived_location
        self.finished_at = newModel.finished_at
        self.finished_location = newModel.finished_location
        self.localSignaturesInfo = newModel.localSignaturesInfo
        self.stc_document = newModel.stc_document
        self.coc_document = newModel.coc_document
        self.invoice_document = newModel.invoice_document
        self.other_document = newModel.other_document
        self.stc_documents = newModel.stc_documents
        self.coc_documents = newModel.coc_documents
        self.notice_of_completion_documents = newModel.notice_of_completion_documents
        self.electrical_template = newModel.electrical_template
        self.is_aus_solar_co = newModel.is_aus_solar_co
        self.physicallyAttended = newModel.physicallyAttended
        self.installer_rating_id = newModel.installer_rating_id
        self.is_aho = newModel.is_aho
        self.is_new_stc_form = newModel.is_new_stc_form
        self.agent_id = newModel.agent_id
        self.re_sign_statement_message = newModel.re_sign_statement_message
        self.gst = newModel.gst
        self.agreenments = newModel.agreenments
        self.delivery_address = newModel.delivery_address
        self.pick_up_required = newModel.pick_up_required
        self.pick_up_reference = newModel.pick_up_reference
        self.installer_job_site_instruction = newModel.installer_job_site_instruction
        //MARK: - 需要被观察的数据放在后边，因为要用到前边赋值的数据，例如is_new_stc_form等
        self.owner_address = newModel.owner_address
        self.install_address = newModel.install_address
        self.system_detail = newModel.system_detail
        self.pvd_checklists = newModel.pvd_checklists
        self.pvd_serial_numbers = newModel.pvd_serial_numbers
        self.pvd_inverter_serial_numbers = newModel.pvd_inverter_serial_numbers
        self.tank_serial_numbers = newModel.tank_serial_numbers
        if self.solar_water_heater {//如果是热水器，将tank数据作为inverter数据处理，通用一套逻辑
            self.pvd_inverter_serial_numbers = newModel.tank_serial_numbers
        }
        self.signatures = newModel.signatures
        //MARK: - 重新整理数据，处理本地数据
        self.getLocalPanelNumber()
        self.getLocalInverterNumber()
        self.getLocalSignature()
        self.dealAndGetLocalChecklist()
    }
    //MARK: - 组织checklist数据，且获取本地数据
    func dealAndGetLocalChecklist(){
        //0.先缓存，在一个增加
        var cacheChecklist = pvd_checklists
        pvd_checklists.removeAll()
        //1.*************Pre-Installation selfie
        if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.preInstall.rawValue
        }){
            //这一组的header
            let header = PVDChecklistModel()
            header.title = R.string.localizable.on_SITESELFIE()
            header.type = ChecklistType.header.rawValue
            header.section = .checkInSelfie
            pvd_checklists.append(header)
            //
            let checkModel = cacheChecklist[findIndex]
            checkModel.section = .checkInSelfie
            pvd_checklists.append(checkModel)//
            cacheChecklist.remove(at: findIndex)//删除
        }
        //2.*************扫描solar的Panel Number和Inverter Number（或者heater的tank serial number）
        //这一组的header
        let barcodeHeader = PVDChecklistModel()
        barcodeHeader.title = R.string.localizable.preinstallationE()//"PRE INSTALLATIONE"
        barcodeHeader.type = ChecklistType.headerWithImage.rawValue
        barcodeHeader.section = .scan
        pvd_checklists.append(barcodeHeader)
        if self.solar_water_heater {
            //panels
            let panelsChecklist = PVDChecklistModel()
            panelsChecklist.id = ChecklistFixedId.tanks.rawValue
            panelsChecklist.title = R.string.localizable.serials("Tank")//"tank Serials"
            panelsChecklist.section = .scan
            panelsChecklist.originalChecklistFlag = false
            pvd_checklists.append(panelsChecklist)
        }else{
            //panels
            let panelsChecklist = PVDChecklistModel()
            panelsChecklist.id = ChecklistFixedId.panels.rawValue
            panelsChecklist.title = R.string.localizable.serials("Panel")//"Panel Serials"
            panelsChecklist.section = .scan
            panelsChecklist.originalChecklistFlag = false
            pvd_checklists.append(panelsChecklist)
            
            //inverters
            let invertersChecklist = PVDChecklistModel()
            invertersChecklist.id = ChecklistFixedId.inverters.rawValue
            invertersChecklist.title = R.string.localizable.serials("Inverter")//"Inverter Serials"
            invertersChecklist.section = .scan
            invertersChecklist.originalChecklistFlag = false
            pvd_checklists.append(invertersChecklist)
        }
        
        //3.*************Mid-Installation selfie
        if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.midInstall.rawValue
        }){
            //这一组的header
            let header = PVDChecklistModel()
            header.title = R.string.localizable.on_SITESELFIE()//"ON_SITE SELFIE"
            header.type = ChecklistType.header.rawValue
            header.section = .midInstallationSelfie
            pvd_checklists.append(header)
            //
            let checkModel = cacheChecklist[findIndex]
            checkModel.section = .midInstallationSelfie
            pvd_checklists.append(checkModel)//
            cacheChecklist.remove(at: findIndex)//删除
        }
        //4.*************checklist
        //Checklist这一组的header
        let checklistHeader = PVDChecklistModel()
        checklistHeader.title = R.string.localizable.checklisT()
        checklistHeader.type = ChecklistType.headerWithImage.rawValue
        checklistHeader.section = .otherChecklist
        pvd_checklists.append(checklistHeader)
        // 暂存endOfInstallationChecklist
        var endOfInstallationChecklist: PVDChecklistModel!
        if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.testAndCommission.rawValue
        }){
            endOfInstallationChecklist = cacheChecklist[findIndex]
            cacheChecklist.remove(at: findIndex)//删除
        }
        // 暂存certificateOfElectricalSafety
        var cesChecklist: PVDChecklistModel!
        if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.certificateOfElectricalSafety.rawValue
        }){
            cesChecklist = cacheChecklist[findIndex]
            cacheChecklist.remove(at: findIndex)//删除
        }
        //将cacheChecklist剩下的都加载Checklist这一组的最后边
        for checkModel in cacheChecklist{
            checkModel.section = .otherChecklist
            pvd_checklists.append(checkModel)
        }
        //  der register加在Checklist最后,
        if self.der_register && self.solar_water_heater == false{//如果开启der register，加入到最后一行行, pvd才有derr，swh没有derr
            let derChecklist = PVDChecklistModel()
            derChecklist.title = R.string.localizable.derRegister()
            derChecklist.is_required = "false"
            derChecklist.type = ChecklistType.DerRegister.rawValue
            derChecklist.section = .otherChecklist
            derChecklist.originalChecklistFlag = false
            pvd_checklists.append(derChecklist)
        }
        //5.*************End of installation
        if let _ = endOfInstallationChecklist{
            //这一组的header
            let header = PVDChecklistModel()
            header.title = R.string.localizable.on_SITESELFIE()//"ON_SITE SELFIE"
            header.type = ChecklistType.header.rawValue
            header.section = .endOfInstallation
            pvd_checklists.append(header)
            //
            endOfInstallationChecklist.section = .endOfInstallation
            pvd_checklists.append(endOfInstallationChecklist)
        }
        //6.*************CERTIFICATES
        //CERTIFICATES这一组的header
        if self.spv_check || self.install_address.state == "WA" || self.coc_documents.count > 0 || cesChecklist != nil {//满足其中之一就会有Certificate 这一组
            var certificateChecklist = [PVDChecklistModel]()//暂存
            let certificatesHeader = PVDChecklistModel()
            certificatesHeader.title = R.string.localizable.certificateS()//"CERTIFICATES"
            certificatesHeader.type = ChecklistType.header.rawValue
            certificatesHeader.section = .certificates
            certificateChecklist.append(certificatesHeader)
            //Panel Installed步骤
            if self.spv_check {//如果开启SPV，将Panel Installed加入到第一行
                let spvChecklist = PVDChecklistModel()
                spvChecklist.is_required = "true"
                spvChecklist.title = R.string.localizable.dateOfCommissioning()//"Date of Commissioning"
                spvChecklist.type = ChecklistType.PanelInstalled.rawValue
                spvChecklist.section =  .certificates
                spvChecklist.answered_at = (self.spv_installed ? DateUtil().getCurrentDatetime() : "")//是否完成
                spvChecklist.originalChecklistFlag = false
                certificateChecklist.append(spvChecklist)
            }
            //Noc只有WA有，点击可以上传
            if self.install_address.state == "WA" && self.solar_water_heater == false{//pvd job才有NOC
                let nocChecklist = PVDChecklistModel()
                nocChecklist.id = ChecklistFixedId.nocAttachment.rawValue
                nocChecklist.is_required = "true"//on_grid才是必填项
                nocChecklist.title = R.string.localizable.noC()
                nocChecklist.type = ChecklistType.Image.rawValue
                nocChecklist.section =  .certificates
                nocChecklist.is_show_photos = true
                nocChecklist.answered_at = (self.notice_of_completion_documents.count > 0 ? DateUtil().getCurrentDatetime() : "")//判断此项是否完成，在这里设置时间是为了统计已经完成的数量，没有其他意义
                nocChecklist.originalChecklistFlag = false
                //将附件附件到images中
                for dataModel in self.notice_of_completion_documents{
                    let imageModel = CheckListImageDBModel()
                    imageModel.id = "\(dataModel.id)"
                    imageModel.image = dataModel.url
                    imageModel.title = dataModel.name
                    nocChecklist.images.append(imageModel)
                }
                certificateChecklist.append(nocChecklist)
            }
            //COC只有QLD是必填项，在retailer段上传，有数据就显示；否则不显示
            if self.coc_documents.count > 0{
                let cocChecklist = PVDChecklistModel()
                cocChecklist.id = ChecklistFixedId.cocAttachment.rawValue
                cocChecklist.is_required = "false"
                cocChecklist.title = R.string.localizable.cocescDocument()//"COC (ESC) Document"
                cocChecklist.type = ChecklistType.Image.rawValue
                cocChecklist.section =  .certificates
                cocChecklist.is_show_photos = true
                cocChecklist.originalChecklistFlag = false
                //将附件附件到images中
                for dataModel in self.coc_documents{
                    let imageModel = CheckListImageDBModel()
                    imageModel.image = dataModel.url
                    imageModel.title = dataModel.name
                    cocChecklist.images.append(imageModel)
                }
                certificateChecklist.append(cocChecklist)
            }
            //End of installation
            if let _ = cesChecklist{
                cesChecklist.section = .certificates
                certificateChecklist.append(cesChecklist)
            }
            //第一个是certificate header，大于1个标识有checklist，才显示
            if certificateChecklist.count > 1 {
                for item in certificateChecklist {
                    pvd_checklists.append(item)
                }
            }
        }
        
        //7.*************SIGNATURES
        //signatures这一组的header
        let signaturesHeader = PVDChecklistModel()
        signaturesHeader.title = R.string.localizable.signatureS()
        signaturesHeader.type = ChecklistType.headerWithImage.rawValue
        signaturesHeader.section = .signatures
        pvd_checklists.append(signaturesHeader)
        if self.solar_water_heater {//heater: 热水器
            //installer
            let installerChecklist = PVDChecklistModel()
            installerChecklist.is_required = "false"
            installerChecklist.type = SignatureType.Installer.rawValue
            installerChecklist.section = .signatures
            installerChecklist.answered_at = self.signatures.installer_signed_at
            installerChecklist.title = self.signatures.installer_full_name
            pvd_checklists.append(installerChecklist)
            //
            let ownerChecklist = PVDChecklistModel()
            ownerChecklist.is_required = "false"
            ownerChecklist.type = SignatureType.Owner.rawValue
            ownerChecklist.section = .signatures
            ownerChecklist.answered_at = self.signatures.owner_signed_at
            var ownerFullName = ""
            if self.signatures.owner_signed_name != "" {
                ownerFullName = self.signatures.owner_signed_name
            }else{
                ownerFullName = self.signatures.owner_type_name
            }
            ownerChecklist.title = ownerFullName
            pvd_checklists.append(ownerChecklist)
        }else{//solar
            if self.is_new_stc_form{//新协议
                if self.isInstallerAndDesigner{//同一个人
                    //installer&designer
                    let installerAndDesignerChecklist = PVDChecklistModel()
                    installerAndDesignerChecklist.is_required = "true"
                    installerAndDesignerChecklist.type = SignatureType.InstallerAndDesiger.rawValue
                    installerAndDesignerChecklist.section = .signatures
                    installerAndDesignerChecklist.answered_at = self.signatures.installer_signed_at
                    installerAndDesignerChecklist.title = self.signatures.installer_full_name
                    pvd_checklists.append(installerAndDesignerChecklist)
                    
                    //owner
                    let ownerChecklist = PVDChecklistModel()
                    ownerChecklist.is_required = "true"
                    ownerChecklist.type = SignatureType.Owner.rawValue
                    ownerChecklist.section = .signatures
                    ownerChecklist.answered_at = self.signatures.owner_signed_at
                    var ownerFullName = ""
                    if self.signatures.owner_signed_name != "" {
                        ownerFullName = self.signatures.owner_signed_name
                    }else{
                        ownerFullName = self.signatures.owner_type_name
                    }
                    ownerChecklist.title = ownerFullName
                    pvd_checklists.append(ownerChecklist)
                }else{
                    //installer
                    let installerChecklist = PVDChecklistModel()
                    installerChecklist.is_required = "true"
                    installerChecklist.type = SignatureType.Installer.rawValue
                    installerChecklist.section = .signatures
                    installerChecklist.answered_at = self.signatures.installer_signed_at
                    installerChecklist.title = self.signatures.installer_full_name
                    pvd_checklists.append(installerChecklist)
                    //Designer
                    let designerChecklist = PVDChecklistModel()
                    designerChecklist.is_required = "true"
                    designerChecklist.type = SignatureType.Designer.rawValue
                    designerChecklist.section = .signatures
                    designerChecklist.answered_at = self.signatures.designer_signed_at
                    designerChecklist.title = self.signatures.designer_full_name
                    pvd_checklists.append(designerChecklist)
                    //
                    let ownerChecklist = PVDChecklistModel()
                    ownerChecklist.is_required = "true"
                    ownerChecklist.type = SignatureType.Owner.rawValue
                    ownerChecklist.section = .signatures
                    ownerChecklist.answered_at = self.signatures.owner_signed_at
                    var ownerFullName = ""
                    if self.signatures.owner_signed_name != "" {
                        ownerFullName = self.signatures.owner_signed_name
                    }else{
                        ownerFullName = self.signatures.owner_type_name
                    }
                    ownerChecklist.title = ownerFullName
                    pvd_checklists.append(ownerChecklist)
                }
            }else{//老协议
                //installer
                let installerChecklist = PVDChecklistModel()
                installerChecklist.is_required = "true"
                installerChecklist.type = SignatureType.Installer.rawValue
                installerChecklist.section = .signatures
                var installerSignedAt = ""
                if let localSign = self.localSignatures.installer{
                    installerSignedAt = localSign.signed_at
                    installerChecklist.localDataflag = true
                    
                }else{
                    installerSignedAt = self.signatures.installer_signed_at
                }
                installerChecklist.answered_at = installerSignedAt
                installerChecklist.title = self.signatures.installer_full_name
                pvd_checklists.append(installerChecklist)
                //Designer
                let designerChecklist = PVDChecklistModel()
                designerChecklist.is_required = "true"
                designerChecklist.type = SignatureType.Designer.rawValue
                designerChecklist.section = .signatures
                var designerSignedAt = ""
                if let localSign = self.localSignatures.designer{
                    designerSignedAt = localSign.signed_at
                    designerChecklist.localDataflag = true
                }else{
                    designerSignedAt = self.signatures.designer_signed_at
                }
                designerChecklist.answered_at = designerSignedAt
                designerChecklist.title = self.signatures.designer_full_name
                pvd_checklists.append(designerChecklist)
                
                let ownerChecklist = PVDChecklistModel()
                ownerChecklist.is_required = "true"
                ownerChecklist.type = SignatureType.Owner.rawValue
                ownerChecklist.section = .signatures
                var ownerSignedAt = ""
                if let localSign = self.localSignatures.owner{
                    ownerSignedAt = localSign.signed_at
                    ownerChecklist.localDataflag = true
                }else{
                    ownerSignedAt = self.signatures.owner_signed_at
                }
                var ownerFullName = ""
                if self.signatures.owner_signed_name != "" {
                    ownerFullName = self.signatures.owner_signed_name
                }else{
                    ownerFullName = self.signatures.owner_type_name
                }
                ownerChecklist.answered_at = ownerSignedAt
                ownerChecklist.title = ownerFullName
                pvd_checklists.append(ownerChecklist)
                //witness
                let witnessChecklist = PVDChecklistModel()
                witnessChecklist.is_required = "false"
                witnessChecklist.type = SignatureType.Witness.rawValue
                witnessChecklist.section = .signatures
                var witnessSignedAt = ""
                var witnessName = ""
                if let localSign = self.localSignatures.owner{
                    witnessSignedAt = localSign.signed_at
                    witnessChecklist.localDataflag = true
                    witnessName = localSign.print_name
                }else{
                    witnessSignedAt = self.signatures.owner_signed_at
                    witnessName = self.signatures.witness_signed_name
                }
                witnessChecklist.answered_at = witnessSignedAt
                witnessChecklist.title = witnessName
                pvd_checklists.append(witnessChecklist)
            }
        }
        if self.solar_water_heater == false{//pvd才有attachment，swh没有
            //8.*************Other attachment
            //attachment这一组的header
            let attachmentHeader = PVDChecklistModel()
            attachmentHeader.title = R.string.localizable.attachmentS()
            attachmentHeader.type = ChecklistType.header.rawValue
            attachmentHeader.section = .otherAttachment
            pvd_checklists.append(attachmentHeader)
            //
            let otherChecklist = PVDChecklistModel()
            otherChecklist.id = ChecklistFixedId.otherAttachment.rawValue
            otherChecklist.is_required = "false"
            otherChecklist.title = R.string.localizable.otherDocuments()
            otherChecklist.type = ChecklistType.Image.rawValue
            otherChecklist.section = .otherAttachment
            otherChecklist.is_show_photos = true
            otherChecklist.originalChecklistFlag = false
            //将附件附件到images中
            for dataModel in self.other_document{
                let imageModel = CheckListImageDBModel()
                imageModel.id = "\(dataModel.id)"
                imageModel.image = dataModel.url
                imageModel.title = dataModel.name
                otherChecklist.images.append(imageModel)
            }
            pvd_checklists.append(otherChecklist)
        }
        //获取本地数据
        self.getLocalCheckList()
        //MARK: - 通知数据更新
        self.broadCastChecklistData()
    }
    func getLocalCheckList(){
        self.localChecklists.removeAll()
        //*********************取消删除重复的image，防止反复上传，再取消上传，网络不好时，重新上传导致的图片丢失
        //0.先获取原始数据
//        self.localChecklists = DBManager.shared.loadAllChecklistData(pvdId: self.id)
        //1.先处理数据，删除已经上传到服务器，但是本地数据还存在的image
//        if self.localChecklists.count > 0 {
//            _ = self.localChecklists.map { localChecklist in
//                if localChecklist.type == ChecklistType.Image.rawValue{//图片类型
//                    _ = self.pvd_checklists.map { serverChecklist in
//                        if localChecklist.id == serverChecklist.id, localChecklist.localAddImages.count > 0 {//相同的checklist
//                            //去除本地图片和server上重复的图片(主要是处理：1.从checklist image list中返回时取消了操作队列，可能存在已经上传但网络回调没有回来的情况。2.Reupload的过程中的取消操作)
//                            _ = localChecklist.localAddImages.map { localImageModel in
//                                _ = serverChecklist.images.map { serverImageModel in
//                                    if localImageModel.record_at == serverImageModel.record_at {
//                                        DBManager.shared.deleteChecklistImageData(model: localImageModel)
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
        //*********************取消删除重复的image，防止反复上传，再取消上传，网络不好时，重新上传导致的图片丢失
        //2.再重新获取数据
        self.localChecklists = DBManager.shared.loadAllChecklistData(pvdId: self.id)
//        if self.localChecklists.count > 0 {
            //MARK: - 将本地数据附加到pvd_checklist上
            _ = self.localChecklists.map { localChecklist in
                _ = self.pvd_checklists.map { serverChecklist in
                    if localChecklist.id == serverChecklist.id {//相同的checklist
                        if localChecklist.type == ChecklistType.Bool.rawValue || localChecklist.type == ChecklistType.Text.rawValue{
                            serverChecklist.dbId = localChecklist.dbId
                            serverChecklist.answer = localChecklist.answer
                            serverChecklist.answered_at = localChecklist.answered_at
                            serverChecklist.oper_type = DataOperType.Add.rawValue
                        }else if localChecklist.type == ChecklistType.Image.rawValue{//图片类型
                            //0.image 降序排列
                            serverChecklist.images = serverChecklist.images.reversed()
                            //1.删除的数据
                            if localChecklist.localDeletedImages.count > 0{
                                //1.将本地已经删除的服务器上的数据，在返回的images list中删除
                                _ = localChecklist.localDeletedImages.map { localImageModel in
                                    if let delIndex = serverChecklist.images.firstIndex(where: {$0.id == localImageModel.id}) {
                                        //不显示已经删除的数据
                                        serverChecklist.images.remove(at: delIndex)
                                        //保存已经删除的数据
                                        serverChecklist.localDeletedImages.append(localImageModel)
                                    }
                                }
                            }
                            //2.增加的数据
                            if localChecklist.localAddImages.count > 0 {
                                //1.将图片附加到image list上,将本地数据附加到到最前边
                                _ = localChecklist.localAddImages.map { localImageModel in
                                      serverChecklist.images.insert(localImageModel, at: 0)
                                    //保存本地新增加的数据
//                                    serverChecklist.localAddImages.append(localImageModel)
                                }
                            }
                        }
                    }
                }
            }
//        }
    }
    //MARK: - 获取本地数据且将新增和修改数据合并到pvd_serial_numbers中，删除的数据单独存放
    func getLocalPanelNumber(){
        //第一步：降序排列
        self.pvd_serial_numbers = self.pvd_serial_numbers.reversed()
        //第二步.处理本地数据
        self.localDeletedSerialNumbers.removeAll()
        
        let localSerialNumbers = DBManager.shared.loadLocalSeriallNumber(pvdId: JobDetailModelHelper.shared.jobDetailModel.id,tableName: panelnumber_table_name)
        
        //1.将reupload时中途cancel时，可能导致本地数据和server上的数据重复的删除掉
        var localAddData = localSerialNumbers.filter { dbModel in
            dbModel.operType == DataOperType.Add.rawValue ? true : false
        }
        //
        let _ = self.pvd_serial_numbers.map({ serverModel in
            if let index = localAddData.firstIndex(where: {$0.code == serverModel.code }){
                let localModel = localAddData[index]
                localAddData.remove(at: index)
                DBManager.shared.deleteLocalBarcodeByCode(tableName: panelnumber_table_name, code: localModel.code)
            }
        })
        //2.将已经删除的过滤掉
        let localDelData = localSerialNumbers.filter { dbModel in
            dbModel.operType == DataOperType.Del.rawValue ? true : false
        }
        for delModel in localDelData {
            if let index =  self.pvd_serial_numbers.firstIndex(where: {$0.id == delModel.id }){
                self.pvd_serial_numbers.remove(at: index)
                self.localDeletedSerialNumbers.append(delModel)
            }
        }
        //3.将修改过的赋值为本地的新值
        let localModifyData = localSerialNumbers.filter { dbModel in
            dbModel.operType == DataOperType.Modify.rawValue ? true : false
        }
        for updModel in localModifyData {
            if let index =  self.pvd_serial_numbers.firstIndex(where: {$0.id == updModel.id  }){
                self.pvd_serial_numbers[index] = updModel
            }
        }
        //4.新增加的放在最前边
        for newModel in localAddData {
            self.pvd_serial_numbers.insert(newModel, at: 0)
        }
        //MARK: - 通知数据更新
        self.broadCastPanelData()
    }
    //MARK: - 获取本地数据且将新增和修改数据合并到pvd_serial_numbers中，删除的数据单独存放
    func getLocalInverterNumber(){
        //第一步：降序排列
        self.pvd_inverter_serial_numbers = self.pvd_inverter_serial_numbers.reversed()
        //第二步.处理本地数据
        self.localDeletedInverterNumbers.removeAll()
        
        let localSerialNumbers = DBManager.shared.loadLocalSeriallNumber(pvdId: JobDetailModelHelper.shared.jobDetailModel.id,tableName: inverternumber_table_name)
        
        //1.将reupload时中途cancel时，可能导致本地数据和server上的数据重复的删除掉
        let localAddData = localSerialNumbers.filter { dbModel in
            dbModel.operType == DataOperType.Add.rawValue ? true : false
        }
        for addModel in localAddData {
            if let index =  self.pvd_inverter_serial_numbers.firstIndex(where: {$0.code == addModel.code }){
                self.pvd_inverter_serial_numbers.remove(at: index)
                DBManager.shared.deleteLocalBarcodeByCode(tableName: inverternumber_table_name, code: addModel.code)
            }
        }
        //2.将已经删除的过滤掉
        let localDelData = localSerialNumbers.filter { dbModel in
            dbModel.operType == DataOperType.Del.rawValue ? true : false
        }
        for delModel in localDelData {
            if let index =  self.pvd_inverter_serial_numbers.firstIndex(where: {$0.id == delModel.id }){
                self.pvd_inverter_serial_numbers.remove(at: index)
                self.localDeletedInverterNumbers.append(delModel)
            }
        }
        //3.将修改过的赋值为本地的新值
        let localModifyData = localSerialNumbers.filter { dbModel in
            dbModel.operType == DataOperType.Modify.rawValue ? true : false
        }
        for updModel in localModifyData {
            if let index =  self.pvd_inverter_serial_numbers.firstIndex(where: {$0.id == updModel.id  }){
                self.pvd_inverter_serial_numbers[index] = updModel
            }
        }
        //4.新增加的放在最前边
        for newModel in localAddData {
            self.pvd_inverter_serial_numbers.insert(newModel, at: 0)
        }
        //MARK: - 通知数据更新
        self.broadCastInverterData()
    }
    //MARK: - 获取本地signature，只有2022-04-01之前的job才有
    fileprivate func getLocalSignature(){
        localSignatures = PVDSignaturesLocalModel()
        let localList = DBManager.shared.loadAllSignatueData(self.id)
        for signatureModel in localList{
            switch signatureModel.signature_type{
            case .Installer:
                localSignatures.installer = signatureModel
            case .Designer:
                localSignatures.designer = signatureModel
            case .Owner:
                localSignatures.owner = signatureModel
            case .Witness:
                localSignatures.witness = signatureModel
            default:
                break
            }
        }
        JobDetailModelHelper.shared.signatures.onNext(signatures)
    }
    //MARK: - 触发checklist数据通知
    func broadCastChecklistData(){
        JobDetailModelHelper.shared.pvd_checklists.onNext(self.pvd_checklists)
    }
    //MARK: - 触发panel number数据通知
    func broadCastPanelData(){
        JobDetailModelHelper.shared.pvd_serial_numbers.onNext(pvd_serial_numbers)
        JobDetailModelHelper.shared.pvd_checklists.onNext(self.pvd_checklists)
    }
    //MARK: - 触发inverter number数据通知
    func broadCastInverterData(){
        JobDetailModelHelper.shared.pvd_inverter_serial_numbers.onNext(pvd_inverter_serial_numbers)
        JobDetailModelHelper.shared.pvd_checklists.onNext(self.pvd_checklists)
    }
}
class PVDDetailAgreenmentsModel: HandyJSON {
    var designer: String?
    var installer: String?
    var owner: String?
    //需要翻墙，因为H5中有s3上的脚本
    //1.installer开头的协议，installer_index.html
    var installerStatementUrlStr: String {
        var urlStr: String = ""//
        if APPConfig.OnlineStatementFlag {//Online
            if let data = installer {
                urlStr = APPConfig.serverAddress + data
            }
        }else {//local,主要用于本地测试
            urlStr = "agreement/installer/installer_index"
        }
        return urlStr
    }
    //2.installer开头的协议，designer_index.html
    var designerStatementUrlStr: String {
        var urlStr: String = ""//本地测试的链接，发布时要删除designer_index.html
        if APPConfig.OnlineStatementFlag {//Online
            if let data = designer {
                urlStr = APPConfig.serverAddress + data
            }
        }else {//local,主要用于本地测试
            urlStr = "agreement/designer/designer_index"
        }
        return urlStr
    }
    //3.owner开头的协议，owner_index.html
    var ownerStatementUrlStr: String {
        var urlStr: String = ""//本地测试的链接，发布时要删除owner_index.html
        if APPConfig.OnlineStatementFlag {//Online
            if let data = owner {
                urlStr = APPConfig.serverAddress + data
            }
        }else {//local,主要用于本地测试
            urlStr = "agreement/owner/owner_index"
        }
        return urlStr
    }
    //老协议is_new_stc_form = false
    let installerOldStatementUrlStr: String = "agreement/installer/installer_index"
    let ownerOldStatementUrlStr: String = "agreement/owner/owner_index"
    required init(){}
}
enum CheckListSectionType: Int {
    case checkInSelfie = 1//checklist中的第一步自拍照
    case scan = 2//panel and inverter
    case midInstallationSelfie = 3//checklist中的第二步自拍照
    case otherChecklist = 4 //去掉三个自拍照的其他checklist
    case endOfInstallation = 5//checklist中的第三步自拍照
    case certificates = 6//整数部分
    case signatures = 7//签名部分
    case otherAttachment = 8// other附件上传
    case none = 0
}
